package com.wosai.teach.fragment;

import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.android.agnetty.constant.HttpCst;
import com.android.agnetty.core.AgnettyFutureListener;
import com.android.agnetty.core.AgnettyResult;
import com.android.agnetty.future.http.HttpFuture;
import com.wosai.teach.R;
import com.wosai.teach.activity.ExpDetailAction;
import com.wosai.teach.activity.LoginActivity;
import com.wosai.teach.adapter.HomeWorkAdapter;
import com.wosai.teach.dao.ExperimentDao;
import com.wosai.teach.handler.HomeWorkHandler;
import com.wosai.teach.handler.UpdateUserHandler;
import com.wosai.teach.oss.OssCallBack;
import com.wosai.teach.oss.OssManager;
import com.wosai.teach.pojo.Experiment;
import com.wosai.teach.pojo.HomeWork;
import com.wosai.teach.pojo.User;
import com.wosai.teach.utils.AppCst;
import com.wosai.teach.utils.AppGlobal;
import com.wosai.teach.utils.C;
import com.wosai.teach.utils.GodUtils;
import com.wosai.teach.utils.ImageLoaders;
import com.wosai.teach.utils.ListViewUtils;
import com.wosai.teach.view.CustomShareBoard;
import com.wosai.teach.view.NoScrollListView;

public class MySelfFragment extends Fragment implements OnClickListener,
		OssCallBack {

	private static Activity activity;
	public static int noautologin;
	private TextView ms_name, ms_hw;
	private static ImageView ms_head;

	private ImageView ms_sex;

	private Button login_out;

	private NoScrollListView homework_list;

	private User user;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.frag_myself, container, false);
		activity = getActivity();
		user = AppGlobal.user;
		if (user != null) {
			initView(view);
			loadHomeInfo();
		}
		return view;
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public void onPause() {
		super.onPause();
	}

	@Override
	public void onStart() {
		super.onStart();
	}

	private void initView(View view) {
		TextView title = (TextView) view.findViewById(R.id.title);
		title.setText("我的");
		title.setOnClickListener(this);

		TextView ms_version = (TextView) view.findViewById(R.id.ms_version);
		ms_version.setText("V " + GodUtils.getVersionName(getActivity()));
		ms_name = (TextView) view.findViewById(R.id.ms_name);
		ms_hw = (TextView) view.findViewById(R.id.ms_hw);
		ms_head = (ImageView) view.findViewById(R.id.ms_head);
		ms_sex = (ImageView) view.findViewById(R.id.ms_sex);
		homework_list = (NoScrollListView) view
				.findViewById(R.id.homework_list);
		ms_name.setText(user.getNickName());
		if (AppGlobal.user.getSex().equals(C.SEX_FEMALE)) {
			ms_sex.setImageResource(R.drawable.girl);
		} else {
			ms_sex.setImageResource(R.drawable.boy);
		}

		ImageLoaders.remove(AppGlobal.user.getIcon1());
		ImageLoaders.getInstance().displayRoundImage(ms_head,
				AppGlobal.user.getIcon1(), R.drawable.login_default_head);

		login_out = (Button) view.findViewById(R.id.login_out);
		login_out.setOnClickListener(this);
		ms_head.setOnClickListener(this);
	}

	private void loadHomeInfo() {
		String url = AppCst.HTTP_URL_HOME_LIST;
		int userId = 0;
		if (AppGlobal.user != null) {
			userId = AppGlobal.user.getUserId();
		}
		url = url.replace("{userId}", userId + "");
		url = url.replace("{pageSize}", 5 + "");
		url = url.replace("{currentPage}", 1 + "");
		System.out.println(url);
		new HttpFuture.Builder(getActivity(), HttpCst.GET).setUrl(url)
				.setHandler(HomeWorkHandler.class)
				.setListener(new AgnettyFutureListener() {
					@Override
					public void onComplete(AgnettyResult result) {
						super.onComplete(result);
						Object rst = result.getAttach();
						if (rst != null && rst instanceof List) {
							List<HomeWork> hwList = (List<HomeWork>) rst;
							exeHomeWork(hwList);
						}
					}

					@Override
					public void onException(AgnettyResult result) {
						super.onException(result);
					}
				}).execute();
	}

	private void exeHomeWork(List<HomeWork> hwList) {
		if (GodUtils.CheckNull(hwList)) {
			return;
		}
		ms_hw.setVisibility(View.VISIBLE);
		HomeWorkAdapter adapter = new HomeWorkAdapter(activity, hwList);
		homework_list.setAdapter(adapter);
		ListViewUtils.setListViewHeightBasedOnChildren(homework_list);
		homework_list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				HomeWork hw = (HomeWork) parent.getAdapter().getItem(position);
				int expId = hw.getExpId();
				ExperimentDao expDao = new ExperimentDao();
				Experiment exp = expDao.getExperimentByExpId(expId);
				Intent it = new Intent(getActivity(), ExpDetailAction.class);
				Bundle bd = new Bundle();
				bd.putSerializable("exp", exp);
				it.putExtras(bd);
				getActivity().startActivity(it);
			}
		});
	}

	@Override
	public void onClick(View v) {
		Intent intent = null;
		switch (v.getId()) {
		case R.id.login_out:
			
			setautologin(1);  
			intent = new Intent(getActivity(), LoginActivity.class);
			startActivity(intent);
//			LoginActivity.backsetautologin();
			getActivity().finish();
			break;
		case R.id.ms_head:
			// 上传头像
			// 激活系统图库，选择一张图片
			intent = new Intent(Intent.ACTION_PICK);
			intent.setType("image/*");
			// 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_GALLERY
			startActivityForResult(intent, C.PHOTO_REQUEST_GALLERY);
			break;
		case R.id.title:
//			this.openShare();
			break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == C.PHOTO_REQUEST_GALLERY) {
			// 从相册返回的数据
			if (data != null) {
				// 得到图片的全路径
				Uri uri = data.getData();
				crop(uri);
			}
		} else if (requestCode == C.PHOTO_REQUEST_CUT) {
			// 从剪切图片返回的数据
			if (data != null) {
				String fileName = getFileName();
				Bitmap bitmap = data.getParcelableExtra("data");
				OssManager.getInstance().asyncUpload(bitmap, "head/", fileName,
						this);// /head/
			}
		}
	}

	private String getFileName() {
//		String[] tt = AppGlobal.user.getIcon1().split("/");
//		String fileName = tt[tt.length - 1];
		Date dd = new Date();
		long time = dd.getTime();
		String fileName = time+"_"+user.getUserId()+".jpg";
		return fileName;
	}

	/**
	 * 分享面板
	 */
	public void openShare() {
		CustomShareBoard shareBoard = new CustomShareBoard(getActivity());
		shareBoard.showAtLocation(getActivity().getWindow().getDecorView(),
				Gravity.BOTTOM, 0, 0);
	}

	/*
	 * 剪切图片
	 */
	private void crop(Uri uri) {
		// 裁剪图片意图
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		// 裁剪框的比例，1：1
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		// 裁剪后输出图片的尺寸大小
		intent.putExtra("outputX", 250);
		intent.putExtra("outputY", 250);

		intent.putExtra("outputFormat", "JPEG");// 图片格式
		intent.putExtra("noFaceDetection", false);// 不取消人脸识别
		intent.putExtra("return-data", true);
		// 开启一个带有返回值的Activity，请求码为PHOTO_REQUEST_CUT
		startActivityForResult(intent, C.PHOTO_REQUEST_CUT);
	}

	private static int UPDATE_HEAD = 1;
	private static Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if (msg.what == UPDATE_HEAD) {
				String path = msg.getData().getString("path");
				ImageLoaders.remove(path);
				ImageLoaders.getInstance().displayRoundImage(ms_head, path,
						R.drawable.login_default_head);
				
				
				
				String url = AppCst.HTTP_USER_INFO_UPDATE;
				int userId = 0;
				if (AppGlobal.user != null) {
					userId = AppGlobal.user.getUserId();
				}
				User user = new User();
				user.setUserId(userId);
				user.setIcon1(path);
//				Content con=(SplashActivity)getActivity();
//				String loginName=SharedSession.get(thisgetActivity(), "d_loginName");
//				String password=SharedSession.get(MySelfFragment.this.getActivity(), "d_password");
				
//				user.setLoginName(SplashActivity.getLoginName());
//				user.setPassword(User.getPassword());
				
				String content =JSON.toJSONString(user); 

//				String content = "{"icon1":"url"}";
				url = url.replace("{userId}", userId + "");
//				.replace("{loginName}", user.getLoginName() + "")
//				.replace("{password}", user.getPassword() + "")
//				.replace("{userName}", UserName() + "")
//				.replace("{nickName}", NickName() + "")
//				.replace("{classId}", classId + "")
//				.replace("{email}", email + "")
//				.replace("{microMsg}", microMsg + "")
//				.replace("{qq}", qq + "")
//				.replace("{mobile}", mobile + "")
//				.replace("{content}", content + "");
//				.replace("{sex}", sex + "");
				System.out.println(url);
				new HttpFuture.Builder(activity, HttpCst.POST).setUrl(url).setData(content)
						.setHandler(UpdateUserHandler.class)
						.setListener(new AgnettyFutureListener() {
							@Override
							public void onComplete(AgnettyResult result) {
								super.onComplete(result);
							}

							@Override
							public void onException(AgnettyResult result) {
								super.onException(result);
							}
						}).execute();
			}
		}
	};

	@Override
	public void callBack(String str) {
		String path = C.OSS_URL + str;
		System.out.println("oss_path||" + path);
		Message msg = new Message();
		msg.what = UPDATE_HEAD;
		msg.getData().putString("path", path);
		handler.sendMessage(msg);

	}
	
	public static void setautologin(int a){
		noautologin=a;
	}
	
	public static int getnoautologin(){
		return noautologin;
	}
}
